package com.cyzy.controller;
import com.cyzy.dto.ApiResponse;
import com.cyzy.service.AiService;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Map;

/**
 * AI聊天控制器
 * @author LIGHT
 */
@RestController
@RequestMapping("/ai")
public class SeekController {
    private static final Logger logger = LoggerFactory.getLogger(SeekController.class);

    @Autowired
    private AiService aiService;

    @GetMapping(value = "/stream")
    public void handleSse(@RequestParam(name = "message") String message, HttpServletResponse response) {
        logger.info("接收到流式请求: {}", message);
        try {
            aiService.streamChat(message, response);
        } catch (IOException e) {
            logger.error("IO异常: ", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (InterruptedException e) {
            logger.error("线程中断异常: ", e);
            Thread.currentThread().interrupt();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            logger.error("处理流式请求异常: ", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping(value = "/chat")
    public ResponseEntity<ApiResponse<Map<String, Object>>> chatWithAi(@RequestBody Map<String, String> requestBody) {
        String message = requestBody.get("message");
        if (message == null || message.trim().isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error("消息内容不能为空"));
        }
        
        logger.info("接收到聊天请求: {}", message);
        
        try {
            Map<String, Object> response = aiService.chat(message);
            if (response.containsKey("error")) {
                return ResponseEntity.ok(ApiResponse.error(500, (String) response.get("error"), response));
            }
            return ResponseEntity.ok(ApiResponse.success(response));
        } catch (Exception e) {
            logger.error("AI聊天异常: ", e);
            return ResponseEntity.ok(ApiResponse.error(500, "AI聊天异常: " + e.getMessage()));
        }
    }

    /**
     * 健康检查接口
     */
//    @GetMapping("/health")
//    public ResponseEntity<ApiResponse<Map<String, String>>> healthCheck() {
//        Map<String, String> status = Map.of("status", "UP", "service", "ai-service");
//        return ResponseEntity.ok(ApiResponse.success(status));
//    }
}
